<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm
        ref="formRef"
        class="mr-[16px]"
        :formList="formList"
        @submit="search"
      />
    </vxe-card>

    <div class="flex-grow overflow-hidden mt-[16px]">
      <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick">
        <template #status_default="{ row }">
          <el-tag :type="formatStatusText(row).status">
            {{ t(formatStatusText(row).text) }}
          </el-tag>
          <span v-if="row.device_status == 1">（{{ row.lock_time }}）</span>
        </template>

        <template #version_default="{ row }">
          {{ row.releaseRecord?.name }}
        </template>
        <template #isUpdate_default="{ row }">
          <el-tag :type="updateHandle(row).status">
            {{ t(updateHandle(row).text) }}
          </el-tag>
        </template>

        <template #topWrap>
          <AuForm
            ref="formCalibrateRef"
            class="top-form mr-[12px]"
            :formList="formCalibrate"
            labelWidth="120px"
            :hiddenBtn="true"
          >
            <template #form_behind>
              <el-col :span="12" class="text-right">
                <el-button type="primary" @click="saveCalibrate">
                  {{ t("store_supervise.form.save") }}
                </el-button>
              </el-col>
            </template>
          </AuForm>
        </template>
      </AuTable>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, h, nextTick, onMounted, reactive, ref } from "vue";
import { AuForm } from "@/components/AuForm";
import { AuTable } from "@/components/AuTable";
import { AuModal } from "@/components/AuModal";
import { ObjectProps, PropDefines } from "@/components/AuTable/type";
import {
  deviceBindStoreId,
  deviceGetList,
  DeviceProp,
  updDeviceStatus,
  updStoreId
} from "@/api/teaInfuser/device";
import { getProvinceCity } from "@/api/user";
import {
  addStore,
  configAdd,
  configGetList,
  configUpd,
  getGroupList,
  getStoreList
} from "@/api/teaInfuser/store";
import { handleTree } from "@/utils/tree";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash-unified";
import { storeGroupSelect } from "@/utils/formSelect";
import StoreModal from "@/views/teaInfuser/device/deviceManage/StoreModal.vue";
import { useRouter } from "vue-router";
import dayjs from "dayjs";
import { DEVICE_TYPE_LIST } from "@/utils/constants";
import { useI18n } from "vue-i18n";

defineOptions({
  name: "StoreSupervise"
});

const { proxy } = getCurrentInstance();
const router = useRouter();
const { t } = useI18n();

// region 页面及组件变量集合
const formList = ref([
  {
    type: "select",
    key: "device_type",
    label: "store_supervise.form.device_type",
    placeholder: "store_supervise.form.enter_device_type",
    valueKey: "value",
    labelKey: "label",
    emptyValues: [null, undefined],
    options: [
      { value: "", label: "store_supervise.form.all_types" },
      ...DEVICE_TYPE_LIST
    ],
    defaultValue: ""
  },
  {
    type: "input",
    key: "device_id",
    label: "store_supervise.form.device_id",
    placeholder: "store_supervise.form.enter_device_id"
  },
  {
    type: "select",
    key: "device_status",
    label: "store_supervise.form.device_status",
    labelKey: "label",
    valueKey: "value",
    columns: [],
    placeholder: "store_supervise.form.select_device_status",
    options: [
      {
        value: "2",
        label: "store_supervise.form.not_activated"
      },
      {
        value: "0",
        label: "store_supervise.form.normal"
      },
      {
        value: "1",
        label: "store_supervise.form.locked"
      }
    ]
  },
  () => storeGroupSelect("group_id", {}, true)
]);
const formCalibrate = ref([
  {
    type: "input",
    key: "min_calibration_interval",
    label: "store_supervise.form.min_calibration_interval",
    formatter: (value: string) => value.replace(/[^0-9]/g, ""),
    parser: (value: string) => value.replace(/[^0-9]/g, ""),
    suffixIcon: h("span", {}, t("store_supervise.form.days")),
    placeholder: "store_supervise.form.enter_min_calibration_interval"
  },
  {
    type: "input",
    key: "min_clear_interval",
    label: "store_supervise.form.min_clear_interval",
    formatter: (value: string) => value.replace(/[^0-9]/g, ""),
    parser: (value: string) => value.replace(/[^0-9]/g, ""),
    suffixIcon: h("span", {}, t("store_supervise.form.days")),
    placeholder: "store_supervise.form.enter_min_clear_interval"
  }
]);

const formMoveData = ref({
  groupId: "",
  store_id: ""
});
const formAcData = ref({
  group_id: "",
  store_id: ""
});

const showAcPopup = ref(false);
const showAddStorePopup = ref(false);
const storeFormData = ref({
  group_id: null,
  id: ""
});

const gridOption = reactive<PropDefines>({
  isServerPage: false,
  columns: [
    { field: "device_id", title: "store_supervise.form.device_id", width: 180 },
    {
      field: "device_type",
      title: "store_supervise.form.device_type",
      width: 120
    },
    {
      field: "store_name",
      title: "store_supervise.form.store_name",
      showOverflow: false
    },
    {
      field: "deviceFormulaUseRecord",
      title: "store_supervise.form.release_version",
      slots: {
        default: "version_default"
      },
      exportMethod: ({ row }) => {
        return row.releaseRecord?.name;
      }
    },
    {
      field: "is_update",
      title: "store_supervise.form.is_update",
      slots: {
        default: "isUpdate_default"
      },
      exportMethod: ({ row }) => {
        return t(updateHandle(row).text);
      }
    },
    { field: "clear_time", title: "store_supervise.form.last_clear_time" },
    {
      field: "calibration_time",
      title: "store_supervise.form.last_calibration_time",
      width: 180,
      showOverflow: false
    }
  ],
  vxeColumnConfig: {
    action: {
      width: 140
    }
  },
  actions: [],
  topTools: [
    // {
    //   key: "lockRecord",
    //   name: "table.lockRecord",
    //   plain: true,
    //   onClick: () => {
    //     // gridRecordOption.columns = [
    //     //   { field: "device_id", title: "设备编码" },
    //     //   { field: "store_name", title: "门店名称" },
    //     //   { field: "lock_time", title: "锁机时间" }
    //     // ];
    //     // showRecordPopup.value = true;
    //     router.push({ name: "StoreSupRecord" });
    //   }
    // }
  ],
  operateTools: [],
  dataSource: [],
  fetchConfig: {
    query: {
      service: async (params: ObjectProps) => {
        const res = await deviceGetList(params);
        let data = res.data;
        if (params.status) {
          data = res.data.filter(v => !v.store_id);
        } else if (params.device_status == "0") {
          data = res.data.filter(v => v.device_status == 0 && v.store_id);
        }
        return {
          ...res,
          data: data,
          pageCount: data.length
        };
      },
      param: () => {
        console.log(formRef.value.getFormData());
        const { group_id, ...rest } = formRef.value.getFormData();
        let group_idlist = [];
        if (group_id != null) {
          group_idlist = group_id.map((item: string) => ({
            group_id: item
          }));
        }
        if (rest.device_status === "2") {
          rest.device_status = null;
          rest.status = 1;
        }
        return {
          ...rest,
          group_idlist: JSON.stringify(group_idlist)
        };
      }
    }
  }
});
const rowData = ref<Partial<DeviceProp>>({});
const showMovePopup = ref(false);
const groupOptions = ref([]);
const storeList = ref([]);

const showRecordPopup = ref(false);
const gridRecordOption = reactive<PropDefines>({
  isServerPage: false,
  columns: [
    { field: "device_id", title: "设备编码" },
    { field: "store_name", title: "门店名称" },
    { field: "activation_time", title: "激活时间" }
  ],
  dataSource: []
});

const provinceCity = ref([]);

let hasCalId = null;
let hasClearId = null;

const formRef = ref();
const formCalibrateRef = ref();
const storeFormRef = ref();
const tableRef = ref();
// endregion

// region 页面公共方法集合
type status = "success" | "warning" | "info" | "primary" | "danger";

function formatStatusText(row: DeviceProp): {
  text: string;
  status: status;
} {
  let text = "",
    status: status = "success";
  if (row.device_status === 0 && row.store_id != null) {
    text = "store_supervise.form.normal";
    status = "success";
  } else if (row.store_id === null) {
    text = "store_supervise.form.not_activated";
    status = "info";
  } else if (row.device_status === 1) {
    text = "store_supervise.form.locked";
    status = "danger";
  }
  return {
    text,
    status
  };
}

function updateHandle(row: DeviceProp): {
  text: string;
  status: status;
} {
  let text = "",
    status: status = "success";
  const useTime = row.deviceFormulaUseRecord?.useTime;
  const releaseTime = row.releaseRecord?.releaseTime;
  if (!useTime) {
    text = "store_supervise.form.not_updated";
    status = "info";
  } else if (dayjs(useTime).isAfter(dayjs(releaseTime))) {
    text = "store_supervise.form.updated";
    status = "success";
  } else {
    text = "store_supervise.form.not_updated";
    status = "info";
  }
  return {
    text,
    status
  };
}

const getMoveList = () => {
  getGroupList({
    start_page: 1,
    size: 0,
    hiddenDeviceType: true
  }).then(res => {
    groupOptions.value = handleTree(res.data, "id", "parent_id");
    if (groupOptions.value.length > 0) {
      getStoreList({
        start_page: 1,
        size: 0,
        group_idlist: JSON.stringify([{ group_id: groupOptions.value[0].id }])
      }).then(storeRes => {
        storeList.value = storeRes.data;
      });
    }
  });

  getProvinceCity().then(res => {
    provinceCity.value = res.data;
  });
};

function handleLock(row: DeviceProp, type: number, note?: string) {
  const param = {
    idlist: JSON.stringify([{ id: row.id }]),
    device_status: type,
    note: note
  };
  updDeviceStatus(param).then(res => {
    ElMessage({
      message: res.message,
      type: "success"
    });
    tableRef.value.refresh();
  });
}

async function getConfigParam() {
  const calRes = await configGetList({
    start_page: 1,
    size: 10,
    key: "min_calibration_interval",
    hiddenDeviceType: true
  });
  if (calRes.data.length) {
    const json = calRes.data[0].value;
    const { day } = JSON.parse(json);
    formCalibrateRef.value.setFormData({
      min_calibration_interval: day
    });
    hasCalId = calRes.data[0].id;
  }
  const clearRes = await configGetList({
    start_page: 1,
    size: 10,
    key: "min_clear_interval",
    hiddenDeviceType: true
  });
  if (clearRes.data.length) {
    const json = clearRes.data[0].value;
    const { day } = JSON.parse(json);
    formCalibrateRef.value.setFormData({
      min_clear_interval: day
    });
    hasClearId = clearRes.data[0].id;
  }
}

// endregion

// region 页面及组件事件集合
const saveCalibrate = () => {
  const calService = hasCalId ? configUpd : configAdd;
  const data = formCalibrateRef.value.getFormData();
  if (data.min_calibration_interval && data.min_calibration_interval > 0) {
    const param = {
      key: "min_calibration_interval",
      value: JSON.stringify({
        day: data.min_calibration_interval
      }),
      note: "最短校准周期",
      id: undefined
    };
    if (hasCalId) {
      param.id = hasCalId;
    }
    calService(param);
  }
  const clearService = hasClearId ? configUpd : configAdd;
  if (data.min_clear_interval && data.min_clear_interval > 0) {
    const param = {
      key: "min_clear_interval",
      value: JSON.stringify({
        day: data.min_clear_interval
      }),
      note: "最短清洗周期",
      id: undefined
    };
    if (hasClearId) {
      param.id = hasClearId;
    }
    clearService(param);
  }
};

const search = () => {
  tableRef.value.vxeGridRef.commitProxy("query");
};

const handleMoveChange = async (val: number) => {
  try {
    const storeRes = await getStoreList({
      start_page: 1,
      size: 0,
      group_idlist: JSON.stringify([{ group_id: val }])
    });
    storeList.value = storeRes.data;
  } catch (e) {
    storeList.value = [];
  }
};

const closeMovePopup = () => {
  showMovePopup.value = false;
};

const handleMoveConfirm = () => {
  if (formMoveData.value.groupId && formMoveData.value.store_id) {
    updStoreId({
      idlist: JSON.stringify([{ device_id: rowData.value.device_id }]),
      store_id: formMoveData.value.store_id
    }).then(res => {
      closeMovePopup();
      ElMessage({
        message: res.message,
        type: "success"
      });
      tableRef.value.vxeGridRef.commitProxy("query");
    });
  } else {
    ElMessage({
      message: t("store_supervise.form.please_select_group_and_store"),
      type: "warning"
    });
  }
};

const handleAcConfirm = () => {
  deviceBindStoreId({
    idlist: JSON.stringify([{ device_id: rowData.value.device_id }]),
    store_id: formAcData.value.store_id
  }).then(res => {
    ElMessage({
      message: res.message,
      type: "success"
    });
    showAcPopup.value = false;
    tableRef.value.refresh();
  });
};

const handleRecordConfirm = () => {
  showRecordPopup.value = false;
};

const addStoreForm = () => {
  showAddStorePopup.value = true;

  nextTick(() => {
    storeFormRef.value.getList();
  });
  // nextTick(() => {
  //   storeFormRef.value.setFormProps(["province", "group_id"], {
  //     province: { options: provinceCity.value },
  //     group_id: { data: groupOptions.value }
  //   });
  // });
};

const handleStoreForm = (data: Record<string, string | number>) => {
  const _data = cloneDeep(data);
  if (!_data.group_id) {
    _data.group_id = 0;
  }
  addStore(_data).then(async res => {
    if (res.data == 0) {
      ElMessage({
        message: t("store_supervise.form.store_name_already_exists"),
        type: "error"
      });
      return;
    }
    ElMessage({
      message: t("store_supervise.form.add_success"),
      type: "success"
    });
    // getGroupList({ size: 0 }).then(response => {
    //   groupOptions.value = handleTree(response.data, "id", "parent_id");
    // });
    storeFormData.value = res.data;
    await handleMoveChange(Number(_data.group_id));
    if (_data.group_id == 0) {
      storeFormData.value.group_id = null;
    } else {
      formAcData.value.group_id = storeFormData.value.group_id;
    }
    formAcData.value.store_id = storeFormData.value.id;
    showAddStorePopup.value = false;
  });
};

const actionClick = ({ key, row }: { key: string; row: DeviceProp }) => {
  rowData.value = row;
  switch (key) {
    case "move":
      showMovePopup.value = true;
      break;
    case "activate":
      showAcPopup.value = true;
      break;
    case "lock":
    case "unlock":
      {
        let status = "激活";
        let type = 0;
        if (row.store_id == null) {
          status = "激活";
          type = 0;
        }
        if (row.device_status == 0) {
          status = "锁定";
          type = 1;
        }
        if (row.device_status == 1) {
          status = "解锁";
          type = 0;
        }
        proxy.$auMessageBox
          .confirm(`确定${status}设备${row.device_id}吗？`, "提示")
          .then(() => {
            if (type === 0) {
              handleLock(row, type, "");
            } else {
              proxy.$auMessageBox
                .prompt("锁机原因", "提示", {
                  inputPlaceholder: "请输入新增的规格标题",
                  inputValidator: (value: string) => {
                    return !(!value || value?.trim() === "");
                  },
                  inputErrorMessage: "规格标题不能为空"
                })
                .then(data => {
                  handleLock(row, type, data.value);
                });
            }
          });
      }
      break;
    default:
      break;
  }
};

onMounted(() => {
  getMoveList();
  getConfigParam();
});

// endregion
</script>

<style lang="scss" scoped>
.active-wrap {
  :deep(.el-descriptions) {
    width: 280px;
    margin: 0 auto;

    .el-descriptions__body .el-descriptions__table:not(.is-bordered) {
      & tr:last-child {
        .el-descriptions__cell {
          padding-bottom: 0;
        }
      }

      .el-descriptions__cell {
        padding-bottom: 20px;
      }
    }
  }
}

.top-form {
  :deep(.el-input__wrapper) {
    padding: 0 11px;
  }
}
</style>
